package com.qianxun.module.datasource1.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianxun.module.datasource1.admin.entity.SysMenuRole;
import com.qianxun.module.datasource1.admin.mapper.SysMenuRoleMapper;
import com.qianxun.module.datasource1.admin.service.SysMenuRoleRelationService;
import com.qianxun.module.datasource1.admin.service.SysMenuRoleService;
import com.qianxun.module.datasource1.admin.service.SysUserMenuRoleRelationService;
import com.qianxun.module.base.bo.ZTreeNode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author admin
 * @since 2019-11-13
 */
@Service
public class SysMenuRoleServiceImpl extends ServiceImpl<SysMenuRoleMapper, SysMenuRole> implements SysMenuRoleService {

    @Resource
    private SysMenuRoleRelationService sysMenuRoleRelationService;

    @Resource
    private SysUserMenuRoleRelationService sysUserMenuRoleRelationService;

    @Override
    public void deleteById(long id) {
        //删除角色和菜单关联
        sysMenuRoleRelationService.removeByRoleId(id);

        //删除本身信息
        removeById(id);
    }

    @Override
    public List<ZTreeNode> searchTreeByUserId(Long userId) {
        List<Long> roleIdList = sysUserMenuRoleRelationService.listRoleIdByUserId(userId);

        List<SysMenuRole> list = list();
        List<ZTreeNode> zTreeNodeList = new ArrayList<>(list.size());
        list.forEach(sysRole -> {
            ZTreeNode zTreeNode = new ZTreeNode();
            zTreeNode.setName(sysRole.getName()).setId(sysRole.getId()).setPId(0L);
            if(roleIdList.contains(sysRole.getId())){
                zTreeNode.setChecked(true).setOpen(true);
            }
            zTreeNodeList.add(zTreeNode);
        });

        zTreeNodeList.add(ZTreeNode.createParent());
        return zTreeNodeList;
    }

    @Override
    public SysMenuRole getOneByName(String menuRoleName) {
        return this.baseMapper.selectOneByName(menuRoleName);
    }
}
